package com.whats.indicator.service.di;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whats.indicator.entity.MainTransformer;
import com.whats.indicator.mapper.MainTransformerMapper;
import com.whats.indicator.service.MainTransformerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MainTransformerDiService implements ApplicationRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(MainTransformerDiService.class);

    @Value("${outter.data.buscenter-mtransformer-url}")
    private String buscenterMtransUrl;
    @Autowired
    private BusCenterTokenService busCenterTokenService;

    @Autowired
    private MainTransformerService mainTransformerService;
    public void acquireTransformerData() {
        String token = busCenterTokenService.getToken();
        if (StrUtil.isBlank(token)) {
            LOGGER.error("acquireTransformerData failed.token is null");
            return;
        }
        // 请求参数
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("psrType", "0301");
        jsonParam.put("distribution", "1");

        JSONObject params = new JSONObject();
        params.put("page", 1);
        params.put("perPage", 400);
        JSONObject filter = new JSONObject();
        filter.put("compare", "=");
        filter.put("fieldName", "psrState");
        filter.put("fieldValue", "20");
        JSONArray filters = new JSONArray();
        filters.add(filter);
        params.put("filters", filters);

        jsonParam.put("params", params);

        LOGGER.info("=======acquireTransformerData url {}", buscenterMtransUrl);
        try {
            String body = HttpUtil.createPost(buscenterMtransUrl)
                    .body(jsonParam.toString()) // 设置请求体
                    .contentType("application/json") // 设置Content-Type
                    .execute().body();
            if (StrUtil.isBlank(body)) {
                LOGGER.error("acquireTransformerData failed.body is null. token is {}", token);
                return;
            }
            JSONObject result;
            List<MainTransformer> mainTransformerList = new ArrayList<>();
            if ((result = JSONUtil.parseObj(body).getJSONObject("result")) != null) {
                JSONArray records;
                if (result.getJSONObject("0301") != null
                        && (records = result.getJSONObject("0301").getJSONArray("records")) != null) {
                    for (Object recordObj : records) {
                        JSONObject jsonObject = JSONUtil.parseObj(recordObj);
                        JSONArray assets = jsonObject.getJSONArray("assets");
                        JSONObject mainTransformerJson = new JSONObject();
                        if (assets != null && !assets.isEmpty()) {
                            mainTransformerJson.putAll(assets.getJSONObject(0));
                        }
                        JSONObject resourceJson = jsonObject.getJSONObject("resource");
                        if (resourceJson != null) {
                            mainTransformerJson.putAll(resourceJson);
                        }
                        MainTransformer mainTransformer = com.alibaba.fastjson.JSONObject.parseObject(mainTransformerJson.toString(), MainTransformer.class);
                        // LOGGER.error("============mainTransformer {}", mainTransformer);
                        mainTransformerList.add(mainTransformer);
                    }

                }
            }
            mainTransformerService.saveOrUpdateBatch(mainTransformerList);
        } catch (Exception e) {
            LOGGER.error("==========acquireTransformerData err", e);
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Thread.sleep(5000);
        LOGGER.info("==========begin acquireTransformerData");
        acquireTransformerData();
    }
}
